<template>
  <div class="pUpload">
    <div class="main flex-column">
      <div class="head flex-none flex-middle">
        <t-image loading="" :src="nowAlbum.coverPictureFileUrl" :style="{ width: '40px', height: '40px' }" fit="cover"
          shape="round" class="mr-10">
          <template #error>
            <img :src="defaultImg" alt="">
          </template>
        </t-image>
        <template v-if="albumList.length">
          <div class="flex-middle">
            <div @click="toPageFn('/?groupId=' + nowAlbum?.groupId)" class="c-success fs-22 flex-none b ">
              {{ nowAlbum.creatorName || '' }}
            </div>
            <template v-if="nowFolder?.subfolderName">
              <div class="fs-22 pl-5 pr-5"> > </div>
              <div class="fs-22 b c-success text-line-1"
                @click="toPageFn(`/?groupId=${nowAlbum?.groupId}&folderId=${nowFolder?._id}`)">
                <span class="b">
                  {{ nowFolder?.subfolderName || '' }}</span>
              </div>
            </template>
            <div class="fs-22 pl-5 pr-5 flex-none"> > </div>
            <div class="fs-22 b flex-none mr-10">照片视频上传</div>
          </div>
          <div class="ml-a flex-middle flex-none" v-if="nowFolder">
            <div class="mr-5">上传到</div>
            <t-select style="width: 150px;" v-model="nowFolder" placeholder="请选择">
              <t-option v-for="item in folderList" :key="item._id" :value="item" :label="item.subfolderName" />
              <!-- 自定义底部内容 -->
              <template #panelBottomContent>
                <t-button @click="getFolder" class="ta-c ml-10" variant="text" theme="primary">
                  <span>没找到？</span><span>刷新下</span>
                </t-button>
              </template>
            </t-select>
            <span class="ml-5">或</span>
            <t-button variant="text" theme="primary" @click="newFolder">新建照片集</t-button>
          </div>
        </template>
      </div>
      <div class="body flex1 of-h flex-column">
        <template v-if="!isRelease">
          <div class="flex1 of-h pf-20 flex-column">
            <t-textarea max v-model="timelineText" placeholder="这一刻的想法…" name="description"
              :autosize="{ minRows: 2, maxRows: 4 }" :maxlength="200" />
            <view class="flex1 of-a flex-wrap">
              <t-upload ref="uploadRef" v-model="media" tips="" v-bind="uploadC" :locale="{
                triggerUploadText: {
                  image: '',
                },
              }" @one-file-fail="handleFail" @success="upSuccess">
                <div class="uploadItem flex-center">
                  <add-icon class="" style="color:#A6A5A5;" />
                </div>
              </t-upload>
              <div class="uploadItem" v-for="(item, index) in mediaList" :key="item.fileId || index">
                <div @click="delItem(index)" class="del">删除</div>
                <div class="uploadStatus flex-center">
                  <CheckIcon class="fs-26" v-if="item.status === 'success'" />
                  <div v-else-if="item.status === 'fail'">失败</div>
                  <div v-else>等待</div>
                </div>
                <img v-if="item.type.startsWith('video')" class="playIcon" src="../../assets/play.png" alt="">
                <t-image loading="" :src="item.preview" fit="cover" shape="round">
                  <template #error>
                    <img :src="defaultImg" alt="">
                  </template>
                </t-image>
              </div>
            </view>
          </div>
          <div class="bottomBar flex-none flex-middle">
            <div class="flex-middle">
              限制上传<span class="c-success">{{ successList.length }}/{{ maxCount }}</span>张，失败<span class="c-success">{{
                failList.length }}</span>张
              <t-button v-if="failList.length" class="ml-20" shape="round" theme="primary" variant="outline"
                @click="reUpload">
                <UploadIcon class="mr-5" />重新上传失败文件
              </t-button>
            </div>
            <t-button @click="toPageFn(-1)" class="ml-a" shape="round" theme="primary" variant="outline">取消</t-button>
            <t-button :disabled="submitDisabled" class="ml-20" shape="round" theme="primary" @click="submit">
              <SendIcon class="rot-330" />确定发布
            </t-button>
          </div>
        </template>
        <template v-else>
          <div class="flex-column flex-center">
            <img class="successImg" src="../../assets/success.png" alt="">
            <div class="fs-22 c-6">发布成功</div>
            <t-button @click="isReleaseSet(false)" class="mt-20" shape="round" theme="primary">继续上传</t-button>
            <t-button @click="toPageFn(-1)" class="mt-20" shape="round" theme="primary" variant="outline">返回</t-button>
          </div>
        </template>
      </div>
    </div>
    <t-loading :loading="releaseLoading" text="发布中..." fullscreen />
    <t-dialog header="请移步小程序新建" :cancel-btn="null" body="网页端新建照片集开发中，请移步群相册云服务小程序新建" :visible="showTips"
      :on-close="hideShowTips" :on-confirm="hideShowTips" />
    <t-dialog v-model:visible="showLeave" header="提示" width="40%" :confirm-on-enter="true" :on-confirm="confirmLeave">
      <t-space direction="vertical" style="width: 100%">
        <div>
          是否离开？
        </div>
      </t-space>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue'
import useAlbumStore from '../index/store/index'
import { storeToRefs } from 'pinia'
import { SendIcon, UploadIcon } from 'tdesign-icons-vue-next'
import { getReq, postReq, baseUrl } from '@/api/request';
import { MessagePlugin } from 'tdesign-vue-next';
import { toPage } from '@/router';
import defaultImg from '@/assets/default.png'
import { AddIcon, CheckIcon } from 'tdesign-icons-vue-next'
const fileObj = {}
const albumStore = useAlbumStore()
const { getAllAlbumGroup, getAlbumFolder, setNowAlbum, uploadOne } = albumStore
const { albumList, folderList, nowAlbum, nowFolder, albumObj } = storeToRefs(albumStore)

const uploadingLength = ref(0)
const maxSize = 1 * 1024 * 1024
const maxCount = 300
const releaseLoading = ref(false)
const uploadC = reactive({
  // max: 10,
  allowUploadDuplicateFile: true,
  theme: 'custom',
  accept: 'image/*,video/*',
  showUploadProgress: true,
  useMockProgress: true,
  mockProgressDuration: 100,
  disabled: false,
  showImageFileName: false,
  multiple: true,
  // sizeLimit: { size: 20, unit: 'B', message: '大小不能超过 {sizeLimit} MB' },
  beforeAllFilesUpload(files) {
    if (mediaList.value.length + files.length > maxCount) {
      MessagePlugin.warning(`最多上传${maxCount}张`)
      return false
    }
    console.log('beforeAllFilesUpload', files)
    uploadingLength.value = files.length
    files.forEach((v, k) => {
      if (fileObj[v.name]) {
        MessagePlugin.warning(`${v.name}文件名称重复，已自动过滤`)
        return false
      }
      if (k + 1 >= maxCount) {
        MessagePlugin.warning(`最多上传${maxCount}张`)
        return false
      } else {
        // 将file转为blobUrl
        v.preview = URL.createObjectURL(v.raw)
        fileObj[v.name] = v
        if (v.size > maxSize) {
          MessagePlugin.warning(`${v.name}文件大小超过${maxSize / 1024 / 1024}MB,已自动过滤`)
          return false
        }
        mediaList.value.push(v)
      }
    })
    return true
  },
  async requestMethod(files) {
    try {
      const res = await uploadOne(files[0], uploadPath)
      uploadingLength.value--
      // if (uploadingLength.value > 0) {
      //   console.error('error')
      //   return { status: 'fail', response: { url: '', fileId: files[0].fileId } }
      // }
      // console.error('success')
      setTimeout(() => {
        getSuccessList()
      }, 0);
      return res
    } catch (error) {
      return { status: 'fail', response: { url: '', fileId: files[0].fileId } }
    }
  },
})
const showTips = ref(false)
const showLeave = ref(false)
const leaveData = ref('')
const timelineText = ref('')
const media = ref([])
const mediaList = ref([])
const mediaFail = ref([])
const isRelease = ref(false)
const failList = ref([])
const successList = ref([])
async function upOne(item, path) {
  item.status = 'uploading'
  const res = await uploadOne(item, path)
  console.error('reup:', res)
  item.status = res.status
  getSuccessList()
  getFailList()
}
function reUpload() {
  failList.value.forEach(item => {
    upOne(item, uploadPath)
  })
}
function isReleaseSet(v) {
  if (v) {
    console.error('remove beforeunload')
    window.removeEventListener('beforeunload', beforeunload);
  } else {
    window.addEventListener('beforeunload', beforeunload);
  }
  isRelease.value = v
}
const getSuccessList = () => {
  successList.value = mediaList.value.filter(item => item.status === 'success')
}
const submitDisabled = computed(() => {
  let res = false
  if (!successList.value.length) {
    return true
  }
  return res || !!uploadingLength.value
})
function delItem(index) {
  mediaList.value.splice(index, 1)
  getSuccessList()
  getFailList()
}
const getFailList = () => {
  failList.value = mediaList.value.filter(item => item.status === 'fail')
}
const uploadPath = computed(() => {
  return 'medias/' + nowAlbum.value.groupId
})
function showTipsSet(v) {
  showTips.value = v
}
function hideShowTips() {
  showTipsSet(false)
}
function newFolder() {
  showTipsSet(true)
}
function getFolder() {
  getAlbumFolder()
}
async function checkText(value) {
  try {
    const res = await getReq('checkTextSecurityForWeb', {
      checkText: value
    })
    if (res.errcode) {
      MessagePlugin.error({
        content: '文本检测不通过，请输入其他内容',
        duration: 1500,
      });
      return Promise.reject(false)
    }
    return res
  } catch (error) {
    return Promise.reject(error)
  }
}
async function submit() {
  releaseLoading.value = true
  try {
    if (timelineText.value) {
      await checkText(timelineText.value)
    }
    const data = {
      groupId: nowAlbum.value.groupId,
      subfolderId: nowFolder.value?._id,
      timelineText: timelineText.value,
      medias: (media.value).map(v => {
        return {
          'fileId': v?.response?.fileId,
          'fileThumbId': '',
          'fileType': v?.type?.startsWith('image') ? 0 : 1
        }
      }),
    }
    const res = await postReq('/uploadMedia', data).catch(e => {
      console.error(e)
    })
    releaseLoading.value = false
    if (res && res.code === 0) {
      MessagePlugin.success({
        content: '操作成功',
      });
      timelineText.value = ''
      media.value = []
      mediaList.value = []
      mediaFail.value = []
      isReleaseSet(true)
      // toPage(location.hash.replace('#/upload', '/'))
    } else {
      MessagePlugin.error({
        content: '操作失败,请稍候重试！',
      });
    }
  } catch (error) {
    releaseLoading.value = false
    console.error(error)
    MessagePlugin.error({
      content: '操作失败,请稍候重试！',
    });
  }

}
function toPageFn(data) {
  if (isRelease.value) {
    toPage(data)
  } else {
    showLeave.value = true
    leaveData.value = data
  }
}
const beforeunload = function (event) {
  event.preventDefault();
  event.returnValue = '';
}
function confirmLeave() {
  showLeave.value = false
  toPage(leaveData.value)
}
function handleFail(res) {
  getFailList()
  return res
}
function upSuccess(res) {
  console.error('一轮上传成功---------------', res)
}
const init = () => {
  window.addEventListener('beforeunload', beforeunload);
  getAllAlbumGroup()
  return
}

onUnmounted(() => {
  window.removeEventListener('beforeunload', beforeunload);
})
init()
</script>

<style lang="scss">
.t-image__error {
  background-image: url("@/assets/video_default.jpg");
  background-size: cover;
}

.t-image__error>* {
  visibility: hidden;
}

.pUpload {
  height: 99.9vh;
  background-color: #F0F0F0;

  .main {
    margin: auto;
    width: 1000px;
    height: 100%;

    .head {
      padding-top: 20px;
      padding-bottom: 20px;
    }

    .body {
      background-color: #fff;
      border-radius: 8px;

      .t-upload__card-box {
        padding: 0;
        width: 125px;
        height: 125px;
      }

      .t-upload__card-image {
        width: 100%;
        height: 100%;

        .t-image {
          object-fit: cover;
        }
      }

      .bottomBar {
        border-top: 1px solid #E3E3E3;
        padding: 20px;
      }
    }

    .c-success {
      color: #3F5EFF;
    }

    .successImg {
      width: 200px;
      height: 200px;
      margin-top: 200px;
    }

  }

  .t-dialog {
    width: 480px !important;
  }

  .uploadItem {
    position: relative;
    width: 125px;
    height: 125px;
    border-radius: 6px;
    background-color: #E6E6E6;
    margin-right: 10px;
    margin-bottom: 10px;

    .t-image {
      width: 125px;
      height: 125px;
    }

    &:hover {
      .del {
        display: block;
      }
    }

    .del {
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 2;
      cursor: pointer;
      color: #fff;
      font-size: 12px;
      background-color: rgba(0, 0, 0, 0.6);
      border-radius: 8px;
      padding: 4px 6px;
      display: none;


    }

    .uploadStatus {
      position: absolute;
      z-index: 2;
      top: 50%;
      left: 0;
      right: 0;
      background-color: rgba(0, 0, 0, 0.6);
      height: 40px;
      color: #fff;
      font-size: 16px;
      transform: translate(0, -50%);
    }

    .t-icon-add {
      font-size: 30px;
    }
  }

  .playIcon {
    position: absolute;
    bottom: 5%;
    left: 50%;
    transform: translate(-50%, 0%);
    width: 30px;
    height: 30px;
    z-index: 2;
  }
}
</style>
